package com.pactera.asmp.server;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Locale;

/**
 * @ProjectName: asmp-server
 * @Package com.pactera.asmp.server
 * @ClassName: MyApplicationContextAware
 * @Description: MyApplicationContextAware
 * @Date 2020/07/02 18:00
 * @Author lvzhiqiang
 * @Version 1.0
 */
public class MyApplicationContextAware implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    @SuppressWarnings("static-access" )
    public void setApplicationContext(ApplicationContext contex)
            throws BeansException {
        // TODO Auto-generated method stub
        this.context = contex;
    }
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }
    public static <T> T getBean(Class<T> type) {
        try {
            return context.getBean(type);
        } catch (NoUniqueBeanDefinitionException e) {   //出现多个，选第一个
            String beanName = context.getBeanNamesForType(type)[0];
            return context.getBean(beanName, type);
        }
    }
    public static String getMessage(String key){
        return context.getMessage(key, null, Locale.getDefault());
    }

}